/**
 * 获取根节点中css里的变量值
 *
 * @param {String} name
 */
function getCssConfig(name) {
    const root = document.documentElement;
    return getComputedStyle(root).getPropertyValue(name).trim();
}

/**
 * 修改根节点中css里的变量值
 *
 * @param {String} name
 * @param {String} value
 */
function updateCssConfig(name, value) {
    document.documentElement.style.setProperty(name, value);
}

/**
 * 重置所有的css变量，不包含背景图相关
 */
function resetCSSLocalStorage() {
    localStorage.removeItem('grid_rows')
    localStorage.removeItem('grid_columns')
    localStorage.removeItem('grid_item_width')
    localStorage.removeItem('grid_item_height')
    localStorage.removeItem('grid_item_content_gap')
    localStorage.removeItem('grid_item_icon_width')
    localStorage.removeItem('grid_item_text_size')
    localStorage.removeItem('grid_item_text_show')
}

/**
 * 获取所有缓存数据，并封装成json对象
 */
function getAllDataFormatJson() {
    let data = {}
    for (let i = 0; i < localStorage.length; i++) {
        let key = localStorage.key(i)
        data[key] = localStorage.getItem(key)
    }
    return data
}

/**
 * 根据导入的json内容，覆写缓存数据
 *
 * @param jsonStr
 * @return {{success: boolean, message: string}}  object
 */
function rewriteDataForJsonFile(jsonStr) {
    let json = JSON.parse(jsonStr);
    if (!json) {
        return {
            success: false,
            message: '数据格式错误'
        }
    }
    for (let key in json) {
        localStorage.setItem(key, json[key])
    }
    return {
        success: true,
        message: '导入成功',
    }
}

/**
 * 读取数据：表格行数
 *
 * @return {Number}
 */
function getGridRows() {
    let value = getCssConfig('--grid-template-rows');
    if (localStorage.getItem('grid_rows')) {
        value = localStorage.getItem('grid_rows')
    }
    return Number(value)
}

/**
 * 读取数据并应用：表格行数
 *
 * @return {Number}
 */
function getAndApplyGridRows() {
    let value = getGridRows();
    updateCssConfig("--grid-template-rows", String(value))
    return Number(value)
}

/**
 * 保存数据到缓存并应用：表格行数
 *
 * @param {Number} value
 */
function saveAndApplyGridRows(value) {
    localStorage.setItem('grid_rows', String(value));
    updateCssConfig("--grid-template-rows", String(value))
}

/**
 * 读取数据：表格列数
 *
 * @return {Number}
 */
function getGridColumns() {
    let value = getCssConfig('--grid-template-columns');
    if (localStorage.getItem('grid_columns')) {
        value = localStorage.getItem('grid_columns')
    }
    return Number(value)
}

/**
 * 读取数据并应用：表格列数
 *
 * @return {Number}
 */
function getAndApplyGridColumns() {
    let value = getGridColumns();
    updateCssConfig("--grid-template-columns", String(value))
    return Number(value)
}

/**
 * 保存数据到缓存并应用：表格列数
 *
 * @param {Number} value
 */
function saveAndApplyGridColumns(value) {
    localStorage.setItem('grid_columns', String(value));
    updateCssConfig("--grid-template-columns", String(value))
}

/**
 * 读取数据：表格单元格宽度
 *
 * @return {String} '0px'
 */
function getGridItemWidth() {
    let value = getCssConfig('--grid-item-width');
    if (localStorage.getItem('grid_item_width')) {
        value = localStorage.getItem('grid_item_width')
    }
    return value
}

/**
 * 读取数据并应用：表格单元格宽度
 *
 * @return {String} '0px'
 */
function getAndApplyGridItemWidth() {
    let value = getGridItemWidth();
    updateCssConfig("--grid-item-width", value)
    return value
}

/**
 * 保存数据到缓存并应用：表格单元格宽度
 *
 * @param {Number} value
 */
function saveAndApplyGridItemWidth(value) {
    localStorage.setItem('grid_item_width', value + 'px');
    updateCssConfig("--grid-item-width", value + 'px')
}

/**
 * 读取数据：表格单元格高度
 *
 * @return {String} '0px'
 */
function getGridItemHeight() {
    let value = getCssConfig('--grid-item-height');
    if (localStorage.getItem('grid_item_height')) {
        value = localStorage.getItem('grid_item_height')
    }
    return value
}

/**
 * 读取数据并应用：表格单元格高度
 *
 * @return {String} '0px'
 */
function getAndApplyGridItemHeight() {
    let value = getGridItemHeight()
    updateCssConfig("--grid-item-height", value)
    return value
}

/**
 * 保存数据到缓存并应用：表格单元格高度
 *
 * @param {Number} value
 */
function saveAndApplyGridItemHeight(value) {
    localStorage.setItem('grid_item_height', value + 'px');
    updateCssConfig("--grid-item-height", value + 'px')
}

/**
 * 读取数据：表格单元格内内容间隔
 *
 * @return {String} '0px'
 */
function getGridItemContentGap() {
    let value = getCssConfig('--grid-item-content-gap');
    if (localStorage.getItem('grid_item_content_gap')) {
        value = localStorage.getItem('grid_item_content_gap')
    }
    return value
}

/**
 * 读取数据并应用：表格单元格内内容间隔
 *
 * @return {String} '0px'
 */
function getAndApplyGridItemContentGap() {
    let value = getGridItemContentGap()
    updateCssConfig("--grid-item-content-gap", value)
    return value
}

/**
 * 保存数据到缓存并应用：表格单元格内内容间隔
 *
 * @param {Number} value
 */
function saveAndApplyGridItemContentGap(value) {
    localStorage.setItem('grid_item_content_gap', value + 'px');
    updateCssConfig("--grid-item-content-gap", value + 'px')
}

/**
 * 读取数据：表格单元格内图标宽度
 *
 * @return {String} '0px'
 */
function getGridItemIconWidth() {
    let value = getCssConfig('--grid-item-icon-width');
    if (localStorage.getItem('grid_item_icon_width')) {
        value = localStorage.getItem('grid_item_icon_width')
    }
    return value
}

/**
 * 读取数据并应用：表格单元格内图标宽度
 *
 * @return {String} '0px'
 */
function getAndApplyGridItemIconWidth() {
    let value = getGridItemIconWidth()
    updateCssConfig("--grid-item-icon-width", value)
    return value
}

/**
 * 保存数据到缓存并应用：表格单元格内图标宽度
 *
 * @param {Number} value
 */
function saveAndApplyGridItemIconWidth(value) {
    localStorage.setItem('grid_item_icon_width', value + 'px');
    updateCssConfig("--grid-item-icon-width", value + 'px')
}

/**
 * 读取数据：表格单元格内字体大小
 *
 * @return {String} '0px'
 */
function getGridItemTextSize() {
    let value = getCssConfig('--grid-item-text-size');
    if (localStorage.getItem('grid_item_text_size')) {
        value = localStorage.getItem('grid_item_text_size')
    }
    return value
}

/**
 * 读取数据并应用：表格单元格内字体大小
 *
 * @return {String} '0px'
 */
function getAndApplyGridItemTextSize() {
    let value = getGridItemTextSize()
    updateCssConfig("--grid-item-text-size", value)
    return value
}

/**
 * 保存数据到缓存并应用：表格单元格内字体大小
 *
 * @param {Number} value
 */
function saveAndApplyGridItemTextSize(value) {
    localStorage.setItem('grid_item_text_size', value + 'px');
    updateCssConfig("--grid-item-text-size", value + 'px')
}

/**
 * 读取数据：表格单元格内文字是否显示
 *
 * @return {String} 'none'、'block'
 */
function getGridItemTextShow() {
    let value = getCssConfig('--grid-item-text-show');
    if (localStorage.getItem('grid_item_text_show')) {
        value = localStorage.getItem('grid_item_text_show')
    }
    return value
}

/**
 * 读取数据并应用：表格单元格内文字是否显示
 *
 * @return {String} 'none'、'block'
 */
function getAndApplyGridItemTextShow() {
    let value = getGridItemTextShow()
    updateCssConfig("--grid-item-text-show", value)
    return value
}

/**
 * 保存数据到缓存并应用：表格单元格内文字是否显示
 *
 * @param {String} value
 */
function saveAndApplyGridItemTextShow(value) {
    localStorage.setItem('grid_item_text_show', value);
    updateCssConfig("--grid-item-text-show", value)
}

/**
 * 读取数据：背景图亮度
 *
 * @return {Number} 0-100
 */
function getBackgroundImageBrightness() {
    let value = getCssConfig('--app-background-image-brightness');
    if (localStorage.getItem('new_tab_bg_brightness')) {
        value = localStorage.getItem('new_tab_bg_brightness')
    } else {
        value = value * 100
    }
    return Number(value)
}

/**
 * 读取数据并应用：背景图亮度
 *
 * @return {Number} 0-100
 */
function getAndApplyBackgroundImageBrightness() {
    let value = getBackgroundImageBrightness();
    updateCssConfig("--app-background-image-brightness", String(value / 100))
    return Number(value)
}

/**
 * 保存数据到缓存并应用：背景图亮度
 *
 * @param {Number} value 0-100
 */
function saveAndApplyBackgroundImageBrightness(value) {
    localStorage.setItem('new_tab_bg_brightness', String(value));
    updateCssConfig("--app-background-image-brightness", String(value / 100))
}

/**
 * 读取数据：背景图
 *
 * @return {String}
 */
function getBackgroundImage() {
    return localStorage.getItem('new_tab_bg');
}

/**
 * 保存本地缓存：背景图
 *
 * @param {String} base64
 */
function saveBackgroundImage(base64) {
    localStorage.setItem('new_tab_bg', base64);
}

/**
 * 获取本地缓存：导航数据
 *
 * @return {Array}
 */
function getStorageNavData() {
    let value = localStorage.getItem('new_tab_page_data');
    if (value) {
        value = JSON.parse(value);
    } else {
        value = []
    }
    return value
}

/**
 * 保存本地缓存：导航数据
 *
 * @param {Array} value
 */
function saveStorageNavData(value) {
    localStorage.setItem('new_tab_page_data', JSON.stringify(value));
}

/**
 * 重新计算导航数据格式，并保存
 *
 * @return {boolean} 数据是否有变动
 */
function recalculateNavData() {
    let navData = getStorageNavData()
    if (navData.length === 0) {
        return false
    }
    let maxNum = getMaxItem()
    let remainList = []
    for (let i = 0; i < navData.length; i++) {
        if (navData[i].items.length > maxNum) {
            remainList.push(...navData[i].items.splice(maxNum))
        }
    }

    if (remainList.length === 0) {
        return false
    }
    // 多余的，添加到新页面去
    while (remainList.length > 0) {
        navData.push({
            pageId: getNewPageId(),
            items: remainList.splice(0, maxNum)
        })
    }
    // 保存
    saveStorageNavData(navData)
    return true
}

/**
 * 获取本地缓存：搜索引擎
 *
 * @return {Array}
 */
function getStorageSearchList() {
    let value = localStorage.getItem('new_tab_search_list');
    if (value) {
        value = JSON.parse(value);
    } else {
        value = [
            {name: '必应', icon: '/src/image/bing.ico', url: 'https://cn.bing.com/search?q='},
            {name: '谷歌', icon: '/src/image/google.png', url: 'https://www.google.com/search?q='},
            {name: '百度', icon: '/src/image/baidu.ico', url: 'https://www.baidu.com/s?wd='}
        ]
    }
    return value
}

/**
 * 保存本地缓存：搜索引擎
 *
 * @param {JSON} value
 * @return {Array} 返回全部引擎列表
 */
function saveStorageSearchItem(value) {
    let list = getStorageSearchList();
    list.push(value);
    localStorage.setItem('new_tab_search_list', JSON.stringify(list));
    return list
}

/**
 * 获取本地缓存：默认搜索引擎
 *
 * @return {JSON}
 */
function getStorageSearchDef() {
    let value = localStorage.getItem('new_tab_search_def');
    if (value) {
        value = JSON.parse(value);
    } else {
        let list = getStorageSearchList();
        value = list[0]
    }
    return value
}

/**
 * 保存本地缓存：默认搜索引擎
 *
 * @param {JSON} value
 */
function saveStorageSearchDef(value) {
    localStorage.setItem('new_tab_search_def', JSON.stringify(value));
}

/**
 * 获取单页最大item数量
 *
 * @return {Number}
 */
function getMaxItem() {
    let rows = getGridRows()
    let columns = getGridColumns()
    return rows * columns
}

/**
 * 获取新收藏项id
 *
 * @return {String}
 */
function getNewId() {
    let id = localStorage.getItem('new_tab_nav_id');
    if (id) {
        id = Number(id) + 1
    } else {
        id = 2
    }
    localStorage.setItem('new_tab_nav_id', String(id))
    return String(id);
}

/**
 * 获取新页面id
 *
 * @return {String}
 */
function getNewPageId() {
    let id = localStorage.getItem('new_tab_nav_page_id');
    if (id) {
        id = Number(id) + 1
    } else {
        id = 2
    }
    localStorage.setItem('new_tab_nav_page_id', String(id))
    return String(id);
}
